package me.spring.cloud.common.components.oss.cloud.util;

import me.spring.cloud.common.components.oss.cloud.CloudStorageService;
import me.spring.cloud.common.components.oss.cloud.exception.OssResourceException;
import me.spring.cloud.common.components.oss.cloud.exception.code.OssCode;
import me.spring.cloud.common.components.oss.cloud.strategy.OssSourceGetStrategy;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OssSourceUtil {

  public static final String OSS_SOURCE_GETSTRATEGY = "ossSourceGetStrategy";

  private static OssSourceGetStrategy ossSourceGetStrategy;

  static final CloudStorageService setOssSourceContext(String keyOssSource) {
    //1.加载CloudStorageService
    CloudStorageService newDataSource = loadDataSource(keyOssSource);

    //2.存储新的CloudStorageService到集合中
    OssSourceSet.putTargetOssSourcesMap(keyOssSource, newDataSource);

    //3.获取CloudStorageService
    return OssSourceSet.getTargetOssSources(keyOssSource);
  }

  /**
   * 从抽象类bean中获取CloudStorageService
   * @param keyOssSource
   * @Return
   */
  static CloudStorageService loadDataSource(String keyOssSource) {
    if (ossSourceGetStrategy == null) {
      synchronized (OssSourceUtil.class) {
        if (ossSourceGetStrategy == null) {
          if (!SpringContextUtils.getContext().containsBeanDefinition(OSS_SOURCE_GETSTRATEGY)) {
            throw new OssResourceException(OssCode.OVERRIDE_GET_OSS_SOURCEINFO);
          }
          ossSourceGetStrategy = (OssSourceGetStrategy) SpringContextUtils.getContext().getBean(OSS_SOURCE_GETSTRATEGY);
        }
      }
    }
    return ossSourceGetStrategy.getOssService(keyOssSource);
  }

  /**
   * @Author luffy
   * @Description 获取CloudStorageService
   * @Date 2019-07-02 11:40
   * @Param [keyOssSource]
   * @Return CloudStorageService
   **/
  public static CloudStorageService getCloudStorageService(String keyOssSource) {
    if (!OssSourceSet.containsOssSource(keyOssSource)) {
      log.debug("正在尝试创建OSS连接[{}] ", keyOssSource);
      return setOssSourceContext(keyOssSource);
    } else {
      return OssSourceSet.getTargetOssSources(keyOssSource);
    }
  }

}